package com.tim.app.ui.fragment.someone_homepage;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.application.library.base.BaseFragment;
import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.HorizontalDividerItemDecoration;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cache.CacheMode;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.entry.Dynamic;
import com.tim.app.server.entry.User;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.DynamicListResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.DynamicDetailActivity;
import com.tim.app.ui.adapter.story.DynamicAdapter;
import com.tim.app.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * 个人说说
 */
public class PersonalSayFragment extends BaseFragment implements View.OnClickListener, LoadMoreHandler, BaseRecyclerAdapter.OnItemClickListener {

    private static final String TAG = "PersonalInfoFragment";
    private View rootView;
    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvDynamic;
    private EmptyLayout emptyLayout;
    private DynamicAdapter adapter;
    private List<Dynamic> dataList;

    private int pageNum = 1;

    User user;

    public static PersonalSayFragment newInstance(User user) {
        PersonalSayFragment newFragment = new PersonalSayFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("user", user);
        newFragment.setArguments(bundle);
        return newFragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_dynamic_fragment, container, false);

            load_more = (LoadMoreRecycleViewContainer) rootView.findViewById(R.id.load_more);
            wrvDynamic = (WrapRecyclerView) rootView.findViewById(R.id.wrvDynamic);

            wrvDynamic.setOverScrollMode(View.OVER_SCROLL_NEVER);

            load_more.useDefaultFooter(View.GONE);
            load_more.setAutoLoadMore(true);
            load_more.setLoadMoreHandler(this);

            emptyLayout = new EmptyLayout(getActivity(), load_more);
            emptyLayout.showLoading();
            emptyLayout.setEmptyDrawable(R.drawable.ic_empty_dynamic);

            if (dataList == null) {
                dataList = new ArrayList<>();
            }
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            wrvDynamic.setLayoutManager(layoutManager);
            wrvDynamic.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(getResources().getColor(R.color.view_background_color)).size((int) getResources().getDimension(R.dimen.dimen_5)).build());
            Bundle args = getArguments();
            if (args != null) {
                user = (User) args.getSerializable("user");
            }
            adapter = new DynamicAdapter(getActivity(), dataList);
            adapter.setOnItemClickListener(this);
            wrvDynamic.setAdapter(adapter);
            updateUserInfo(user);
        }
        initData();
        EventManager.ins().registListener(EventTag.ON_DYNAMIC_DELETED, eventListener);
        EventManager.ins().registListener(EventTag.ON_DYNAMIC_ADD, eventListener);
        return rootView;
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ON_DYNAMIC_DELETED:
                    String deleteId = (String) dataobj;
                    for (int i = 0; i < dataList.size(); i++) {
                        if (dataList.get(i).getId().equals(deleteId)) {
                            dataList.remove(i);
                            adapter.notifyDataSetChanged();
                        }
                    }
                    break;
                case EventTag.ON_DYNAMIC_ADD:
                    initData();
                    break;
            }
        }
    };

    public void updateUserInfo(User user) {
        this.user = user;
        if (UserManager.ins().isLogin() && UserManager.ins().getUserId().equals(user.getUserId())) {
            emptyLayout.setEmptyText(getString(R.string.emptyDynamic), getString(R.string.otherDynamicEmpty));
        } else {
            String emptyText = "";
            if (user.getSex() == 1) {
                emptyText = "他还没有发布过说说";
            } else {
                emptyText = "她还没有发布过说说";
            }
            emptyLayout.setEmptyText(emptyText, "");
        }
    }


    private void initData() {
        pageNum = 1;
        API_Found.ins().getSomeoneSpeakList(TAG, user.getUserId(), pageNum, AppKey.PAGE_SIZE, CacheMode.REQUEST_FAILED_READ_CACHE, refreshCallback);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != rootView && null != rootView.getParent()) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
        EventManager.ins().removeListener(EventTag.ON_DYNAMIC_DELETED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_DYNAMIC_ADD, eventListener);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        }
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        DynamicDetailActivity.start(getContext(), dataList.get(position), false);
    }

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        API_Found.ins().getSomeoneSpeakList(TAG, user.getUserId(), pageNum + 1, AppKey.PAGE_SIZE, CacheMode.REQUEST_FAILED_READ_CACHE, moreCallback);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errcode, String errMsg, int id, boolean fromcache) {
            if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                if (dataList != null) {
                    dataList.clear();
                }
                DynamicListResult result = new Gson().fromJson(resultValue, DynamicListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    pageNum = result.getRes().getArraylist().getCurrentPageNo();
                    if (pageNum != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                }

                if (dataList == null || dataList.size() == 0) {
                    emptyLayout.showEmpty();
                } else {
                    emptyLayout.showContent();
                }
            } else {
                emptyLayout.showEmptyOrError(errcode);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errcode, String errMsg, int id, boolean fromcache) {
            if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                DynamicListResult result = new Gson().fromJson(resultValue, DynamicListResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    pageNum = result.getRes().getArraylist().getCurrentPageNo();
                    if (pageNum != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                }
            } else {
                emptyLayout.showEmptyOrError(errcode);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

}
